package com.bi.bitest.bao.service;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.support.v4.content.LocalBroadcastManager;
import com.bi.bitest.bao.Constants;

/**
 * Created
 * Author:bi[FR]
 * Date:15-10-25
 */
public class PlayService extends Service {
    private MediaPlayer mPlayer;
    private LocalBroadcastManager lbMgr;
    private SeektoReceiver seekReceiver;
    private int sumLen;
    private boolean sendkai=false;

    public void onCreate() {
        super.onCreate();

        mPlayer =new MediaPlayer();
        lbMgr = LocalBroadcastManager.getInstance(getApplicationContext());
        seekReceiver=new SeektoReceiver();
        lbMgr.registerReceiver(seekReceiver, new IntentFilter(Constants.ACTION_SEEKTO));

    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if(intent.getBooleanExtra(Constants.EXTRA_CHANGE, false)){
            try {

               mPlayer.reset();
                //设置新的数据源（新的音频文件）,进入initial初始化状态
                mPlayer.setDataSource(intent.getStringExtra("songLink"));

                mPlayer.prepare();//进入就绪状态（Prepared）

                Intent intentkai = new Intent(Constants.ACTION_PROGRESS);
                intentkai.putExtra(Constants.EXTRA_PROGREES_MAX, 0); // 总时长
                intentkai.putExtra(Constants.EXTRA_PROGREES_CUR, 0);// 当前进度
                intentkai.putExtra("kai",true);
                lbMgr.sendBroadcast(intentkai);

            }  catch (Exception e) {
                e.printStackTrace();
            }
        }
        // 判断当前的MediaPlayer是否正在播放
        if (mPlayer.isPlaying()) {
            mPlayer.pause(); // 暂停
        } else {
            mPlayer.start(); // 播放

            new ProgressThread().start();// 启动计算播放进度的线程
        }
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mPlayer.stop();
        mPlayer.release();// 释放资源
        lbMgr.unregisterReceiver(seekReceiver); //注销广播接收器
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    /**
     * 定义计算播放进度的线程类
     *
     * @author apple
     *
     */
    class ProgressThread extends Thread {
        @Override
        public void run() {
            try {
                while (mPlayer != null && mPlayer.isPlaying()) {
                    sumLen = mPlayer.getDuration();// 获取播放文件的总时长，单位：毫秒
                    int currentPosition = mPlayer.getCurrentPosition(); // 获取当前播放的位置


                    // 准备发送进度广播
                    Intent intent = new Intent(Constants.ACTION_PROGRESS);
                    intent.putExtra(Constants.EXTRA_PROGREES_MAX, sumLen); // 总时长
                    intent.putExtra(Constants.EXTRA_PROGREES_CUR, currentPosition);// 当前进度
                    intent.putExtra("kai",false);
                    lbMgr.sendBroadcast(intent);// 发送播放的进度广播
                    Thread.sleep(400);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    class SeektoReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
            int seekPosition=intent.getIntExtra(Constants.EXTRA_PROGREES_CUR, 0);

            mPlayer.seekTo(seekPosition);//设置播放器的播放位置
        }
    }
}
